<?php
class Controller_Cppa extends Controller 
{
    public function action_report ()
    {
        $post = $this->request->post();
//        Kohana::$log->add(Log::DEBUG, '这是post函数___'.print_r($post, TRUE));
        Kohana::$log->add('DEBUG', '我在开监控sdk：：'.json_encode($_GET).'___'.json_encode($_POST));

        //获取的json字符串
        $json = $post['json'];
//        $json= '{"channel":"10181","applicationInfo":{"19":{"packageName":"com.baidu","appName":" 百度浏览器 ","versionName":"1.0.41342"},"17":{"packageName":"com.use100411","appName":"用户上传1","versionName":"5.2.1"},"18":{"packageName":"com.use100412","appName":"用户上传1","versionName":"4.4.2"},"15":{"packageName":"com.sohu.sohuvideo","appName":"搜狐视频","versionName":"4.5.1"},"16":{"packageName":"com.tencent.mm","appName":"微信","versionName":"5.4.0.51_r798589"},"13":{"packageName":"com.myzaker.ZAKER_Phone","appName":"ZAKER","versionName":"4.4.3"},"14":{"packageName":"com.qvod.player","appName":"快播","versionName":"3.4.19"},"11":{"packageName":"com.iflytek.tts","appName":"讯飞语音合成","versionName":"1.0"},"12":{"packageName":"com.ijinshan.ShouJiKongService","appName":"金山手机助手","versionName":"3.6.0"},"3":{"packageName":"com.baidu","appName":"百度","versionName":"1.0"},"20":{"packageName":"pocket.xdf","appName":"掌上新东方","versionName":"2.1.1"},"2":{"packageName":"com.adobe.flashplayer","appName":"Adobe Flash Player 11.1","versionName":"11.1.115.81"},"10":{"packageName":"com.taobao","appName":"淘宝","versionName":"5.0.1637"},"1":{"packageName":"com.CPPA.feedback","appName":"Feedback","versionName":"1.1.0"},"0":{"packageName":"cn.eoe.app","appName":"eoe","versionName":"1.1.0"},"7":{"packageName":"com.dajie.official","appName":"大街","versionName":"2.0.0"},"6":{"packageName":"com.chaozh.iReaderFree","appName":"掌阅iReader","versionName":"3.4.1"},"5":{"packageName":"com.baidu.searchbox","appName":"百度","versionName":"5.5"},"4":{"packageName":"com.appchina.paydemo","appName":"PayDemo","versionName":"1.0"},"9":{"packageName":"com.example.teacherhelper","appName":"TeacherHelper","versionName":"1.0"},"8":{"packageName":"com.eg.android.AlipayGphone","appName":"支付宝钱包","versionName":"8.2.0.071702"}},"imsi":"460026101349176","imei":"868376010085202","brand":"Lenovo","product":"A708t"}';
        //Kohana::$log->add(Log::DEBUG, '这是JSON___'.$json);
        //把json字符串解析成数组
        $arr_json = json_decode($json,true);
//        var_dump($arr_json);exit;
        //获取json中的IMEI，IMSI，和应用信息
        $imei    = $arr_json['imei'];
        $imsi    = $arr_json['imsi'];
	$brand   = $arr_json['brand'];
        $product = $arr_json['product'];
	$channel = empty($arr_json['channel'])?0:$arr_json['channel'];
        if($channel == 140922)
        {
            $channel = 0;
        }
	$ip      = $this->getIp();
        $applicationInfo = $arr_json['applicationInfo'];
        if(empty($imei))
        {
            echo 'FAILURE';
            throw new Exception("IMEI号不能为空！");
        }
        if(CPPA_Cppa::isChannel($channel)){
            //将IMEI号，和IMSI号存入到数据库（以IMEI号为准），如果已经存在该IMEI号则更新IMSI和时间。
            $time = time();
            //Kohana::$log->add(Log::DEBUG, '这是IMEI___'.$imei);
            //记录每天的活跃数（即每天一共有多少机器上报数据）
            CPPA_Cppa::record_active($imei,$channel,$time);
            CPPA_Cppa::record_apks_active($applicationInfo,$time,$channel);
            //记录每台上班手机的附加信息
            CPPA_Cppa::record_imei($imei,$imsi,$brand,$product,$channel,$time,$ip);
            //记录不同渠道下，不同IMEI，不同pkgname信息。本表是去重以后的表，每一个channel+imei+packagename都是唯一的。
            CPPA_Cppa::record_applicationInfo($imei,$applicationInfo,$time,$channel,$ip);
        }
        //返回OK
        echo "OK";
    }
    
    /**
     * 收集广告客户端，上传的广告日志。
     */
    public function action_report_ad (){
        $post = $this->request->post();
        Kohana::$log->add('DEBUG', '我在广告日志收集中：：'.json_encode($_GET).'___'.json_encode($_POST));

        //获取的json字符串
        $json = $post['json_ad'];
        
        //解析json数据
        $arr_json    = json_decode($json,true);
        $imei        = $arr_json['imei'];
        $time        = $arr_json['time'];
	$type        = $arr_json['type'];
        $notify_id   = $arr_json['notify_id'];
        
        CPPA_Cppa::record_ad_log($imei,$time,$type,$notify_id);
    }
	
    private function getIp() {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $onlineip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $onlineip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }
        return $onlineip;
    }
    
     public function action_build_pkg (){  
//        $arr = array(
//            '0' => '0',
//            '1' => '10100',
//            '2' => '10101',
//            '3' => '10102',
//            '4' => '10103',
//            '5' => '10104',
//        );
//        
//        foreach ($arr as $key => $value) {
//            self::build($value);
//        }
//        $a = 10040;
//        while ($a<10100){
//            self::build($a);
//            $a++;
//        }
        self::build(10182);
        echo "done";
     }
     
     private  function build($uid)
     {
        self::unpack();
        self::reumeng($uid);
        self::reuid($uid);
        self::rebuild($uid);
     }
     //
     private function unpack()
     {
//         system('rd/s/q  feedback_null');
         system('rd/s/q  D:\output\temp');
//         system("apktool d feedback_null.apk");
         system('mkdir D:\output\temp');
         system('xcopy  feedback_null\* D:\output\temp /s');
//         system('rd/s/q  feedback_null');
     }
     
     private function reumeng($uid)
     {
        $f= fopen("D:/output/temp/AndroidManifest.xml","r");
        $f1= fopen("D:/output/temp/AndroidManifest.xml.tmp","w");
        while (!feof($f)){
            $line = fgets($f);
            if(strstr($line, 'UMENG_CHANNEL'))
            {
                fwrite($f1,str_replace("feed0001", $uid, $line));
            }else{
                fwrite($f1, $line);
            }
        }
        fclose($f);
        fclose($f1);
     }
     
     private function reuid($uid)
     {
        $f= fopen("D:/output/temp/AndroidManifest.xml.tmp","r");
        $f1= fopen("D:/output/temp/AndroidManifest.xml.tmp1","w");
        while (!feof($f)){
            $line = fgets($f);
            if(strstr($line, 'UID'))
            {
                fwrite($f1,str_replace("0", $uid, $line));
            }else{
                fwrite($f1, $line);
            }
        }
        fclose($f);
        fclose($f1);
     }
     
     private function rebuild($uid)
     {
        system('del  D:\output\temp\AndroidManifest.xml');
        system('del  D:\output\temp\AndroidManifest.xml.tmp');
        system('rename D:\output\temp\AndroidManifest.xml.tmp1 AndroidManifest.xml');
        system('apktool b D:\output\temp D:\output\temp\feedback_'.$uid.'_unsign.apk');
        system('jarsigner -sigalg MD5withRSA -digestalg SHA1 -verbose -keystore demo.keystore -storepass feedback -keypass feedback -signedjar D:\output\temp\feedback_'.$uid.'.apk D:\output\temp\feedback_'.$uid.'_unsign.apk demo.keystore');
        system('del  D:\output\temp\feedback_'.$uid.'_unsign.apk');
//        system("zipalign 4 /opt/tools/yyh/output/"+name+"/feedback_"+code+"_signed.apk /opt/tools/yyh/output/"+name+"/feedback_"+code+".apk"); 
        system('copy  D:\output\temp\feedback_'.$uid.'.apk D:\output\package');
        system('rd/s/q  D:\output\temp');
     }
    
}
